<template>
  <div class="app-container">
    <!-- <el-tabs>
      <el-tab-pane>房东</el-tab-pane>
      <el-tab-pane>地区</el-tab-pane>
    </el-tabs> -->
    <el-row :gutter="20" class="main-content">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="20" min-size="15">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>

<!--        房产数据-->
        <pane size="80" min-size="70">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px" class="search-form">

              <el-form-item label="房东姓名" prop="landlordName">
                <el-input
                  v-model="queryParams.landlordName"
                  placeholder="请输入房东姓名"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="房东手机号" prop="landlordPhone">
                <el-input
                  v-model="queryParams.landlordPhone"
                  placeholder="请输入房东手机号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="门禁编码" prop="door">
                <el-input
                  v-model="queryParams.door"
                  placeholder="请输入门禁编码"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker clearable
                                v-model="queryParams.startDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择开始日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker clearable
                                v-model="queryParams.endDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择结束日期">
                </el-date-picker>
              </el-form-item>
              <!-- <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="queryParams.remark"
                  placeholder="请输入备注关键词"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                >导出</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="info"
                  plain
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleImport"
                >导入</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange" border v-sticky-header="{ offset: 400 }">
              <el-table-column label="省份" align="left" prop="provinceName"></el-table-column>
              <el-table-column label="城市" align="left" prop="cityName"></el-table-column>
              <el-table-column label="区县" align="left" prop="districtName"></el-table-column>
              <el-table-column label="街道" align="left" prop="streetName"></el-table-column>
              <el-table-column label="村" align="left" prop="villageName"></el-table-column>
              <el-table-column label="地址信息" align="left" prop="address" width="160">
              </el-table-column>
              <el-table-column label="门禁编码" align="center" prop="door" />
              <el-table-column label="开始日期" align="center" prop="startDate" width="100">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="截止日期" align="center" prop="endDate" width="100">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="房东" align="center" prop="landlordName" />
              <el-table-column label="房东手机号" align="center" prop="landlordPhone" />
              <el-table-column label="余额" align="center" prop="balance">
                <template slot-scope="scope">
                  <span>{{ scope.row.balance ? '¥' + scope.row.balance.toFixed(2) : '¥0.00' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="月租" align="center" prop="monthPrice" />
              <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
              <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-document"
                    @click="handleDocuments(scope.row)"
                  >资料管理</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>


    <!-- 添加或修改账单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址选择" prop="addressNode" required>
              <el-cascader
                v-model="form.addressNode"
                :options="addressTreeOptions"
                :props="{ checkStrictly: false, emitPath: true, expandTrigger: 'hover' }"
                clearable
                style="width: 100%"
                placeholder="请选择地址"
                @change="handleAddressNodeSelect"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="门禁编码" prop="door">
              <el-input v-model="form.door" placeholder="请输入门禁编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="月租" prop="monthPrice">
              <el-input v-model="form.monthPrice" placeholder="请输入月租" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="余额" prop="balance">
              <el-input v-model="form.balance" placeholder="请输入余额" type="number" step="0.01" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="endDate">
              <el-date-picker
                clearable
                v-model="form.endDate"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="请选择截止日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="房东" prop="landlordId">
              <el-select
                v-model="form.landlordObj"
                :key="'landlord-select-' + (form.landlordObj ? form.landlordObj.id : 'empty')"
                placeholder="请输入房东姓名搜索"
                style="width: 100%"
                filterable
                remote
                reserve-keyword
                :remote-method="searchLandlord"
                :loading="landlordSearchLoading"
                :default-first-option="false"
                value-key="id"
                @change="handleLandlordChange"
                clearable
                :popper-append-to-body="false">
                <el-option
                  v-for="item in landlordOptions"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-cascader
                v-model="form.deptId"
                :options="enabledDeptOptions"
                :props="{ checkStrictly: true, value: 'id', label: 'label', emitPath: false }"
                clearable
                style="width: 100%"
                placeholder="请选择所属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 房产导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body :close-on-click-modal="false">
      <div class="import-container">
        <div class="import-tips" v-if="!upload.isUploading && !upload.isProcessing">
          <p>请先下载房产导入模板，按照模板格式填写数据后导入：</p>
          <el-button type="text" icon="el-icon-download" @click="importTemplate">下载模板</el-button>
        </div>

        <!-- 文件选择区域 -->
        <div v-if="!upload.isUploading && !upload.isProcessing">
          <el-divider content-position="center">选择文件</el-divider>
          <div class="file-info" v-if="uploadFileName">
            <i class="el-icon-document"></i>
            <span>{{ uploadFileName }}</span>
            <el-button type="text" icon="el-icon-delete" @click="clearUploadFile">清除</el-button>
          </div>
          <div class="upload-area" v-else @click="triggerFileInput">
            <input type="file" ref="fileInput" accept=".xlsx, .xls" style="display: none;" @change="handleFileChange" />
            <i class="el-icon-upload"></i>
            <div class="upload-text">点击选择Excel文件</div>
            <div class="upload-tip">仅支持.xlsx和.xls格式</div>
          </div>
        </div>

        <!-- 导入进度区域 -->
        <div v-if="upload.isUploading" class="import-progress">
          <div class="progress-header">
            <i class="el-icon-loading"></i>
            <span>{{ upload.statusText }}</span>
          </div>

                     <el-progress
             :percentage="upload.progress"
             :status="upload.progressStatus || undefined"
             :stroke-width="12"
             :show-text="true"
           ></el-progress>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitImport"
          :loading="upload.isUploading"
          :disabled="!uploadFile || upload.isUploading"
        >
          {{ upload.isUploading ? '导入中...' : '确 定' }}
        </el-button>
        <el-button
          @click="closeImportDialog"
          :disabled="upload.isUploading"
        >
          {{ upload.isUploading ? '处理中...' : '取 消' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse, exportHouse, importTemplate, importData } from "@/api/door/house"
import { listLandlordAllocated } from '@/api/login'
import { getDicts } from "@/api/system/dict/data"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {deptTreeSelect, getUser} from "@/api/system/user";
import { getToken } from "@/utils/auth"

export default {
  name: "House",
  components: { Splitpanes, Pane },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房产表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 部门名称
      deptName: "",
      // 部门树配置选项
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 省份选项
      provinceOptions: [],
      // 城市选项
      cityOptions: [],
      // 区县选项
      districtOptions: [],
      // 街道选项
      streetOptions: [],
      // 村选项
      villageOptions: [],
      // 表单中的省份选项
      cityOptionsForm: [],
      // 表单中的区县选项
      districtOptionsForm: [],
      // 表单中的街道选项
      streetOptionsForm: [],
      // 表单中的村选项
      villageOptionsForm: [],
      // 地址树形选项
      addressTreeOptions: [
      ],
      // 房东选项
      landlordOptions: [],
      // 房东搜索加载状态
      landlordSearchLoading: false,
      // 上传的文件
      uploadFile: null,
      // 上传文件名
      uploadFileName: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        country: "",
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        address: null,
        door: null,
        accessNum: null,
        monthPrice: null,
        startDate: null,
        endDate: null,
        landlordId: null,
        landlordName: null,
        landlordPhone: null,
        deptId: null,
        remark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        addressNode: [
          { required: true, message: "地址选择不能为空", trigger: "change" }
        ],
        province: [
          { required: true, message: "省份不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "城市不能为空", trigger: "change" }
        ],
        district: [
          { required: true, message: "区县不能为空", trigger: "change" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        landlordId: [
          { required: true, message: "房东不能为空", trigger: "change" }
        ],
        balance: [
          { pattern: /^-?[0-9]+(\.[0-9]{1,2})?$/, message: "余额格式不正确，最多保留两位小数", trigger: "blur" }
        ],
        remark: [
          { max: 500, message: "备注长度不能超过500个字符", trigger: "blur" }
        ]
      },
      // 房产导入参数
      upload: {
        // 是否显示弹出层（房产导入）
        open: false,
        // 弹出层标题（房产导入）
        title: "",
        // 是否正在导入
        isUploading: false,
        // 当前状态文本
        statusText: "准备上传文件...",
        // 进度百分比
        progress: 0,
        // 进度状态
        progressStatus: null
      },
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getDeptTree()
    this.getProvinceOptions()

    // 移除自动加载所有房东，改为搜索时加载
    // 处理URL参数
    if (this.$route.query.landlordId) {
      this.queryParams.landlordId = Number(this.$route.query.landlordId)
      // 如果有房东ID，加载对应的房东信息
      this.loadLandlordById(this.queryParams.landlordId)
    }

    if (this.$route.query.landlordName) {
      // 如果有房东名称参数，可以预先搜索
      this.searchLandlord(this.$route.query.landlordName)
    }
  },
  mounted() {
    // 页面加载后默认选中公司节点，但不触发数据请求
    this.$nextTick(() => {
      if (this.deptOptions && this.deptOptions.length > 0) {
        const companyNode = this.deptOptions[0]
        // 只设置当前选中节点，但不触发handleNodeClick
        this.$refs.tree.setCurrentKey(companyNode.id)

        // 设置部门ID，稍后在getDeptTree完成后会统一请求一次数据
        this.queryParams.deptId = companyNode.id
      }
    })
  },

  methods: {
    /** 查询房产列表 */
    getList() {
      this.loading = true
      console.log(this.queryParams,'queryParams')
      listHouse(this.queryParams).then(response => {
        // 处理房东名称显示
        if (response.rows && response.rows.length > 0) {
          response.rows.forEach(item => {
            // 确保数值字段为数值类型
            item.province = item.province ? Number(item.province) : null
            item.city = item.city ? Number(item.city) : null
            item.district = item.district ? Number(item.district) : null
            item.street = item.street ? Number(item.street) : null
            item.village = item.village ? Number(item.village) : null
            // item.landlordId = item.landlordId ? Number(item.landlordId) : null
            console.log(item.landlordId,'item')
            // 处理房东名称显示 - 确保类型一致性
            if (item.landlordId) {
              // 转换为数值类型进行比较
              const landlordId = Number(item.landlordId)
              const landlord = this.landlordOptions.find(l => Number(l.id) === landlordId)
              if (landlord) {
                item.landlordName = landlord.name
              }
            }

            // 确保余额字段为数值类型
            item.balance = item.balance ? Number(item.balance) : 0
          })
        }
        this.houseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))

        // 使用部门树数据构建地址树
        this.buildAddressTreeFromDeptTree()

        this.$nextTick(() => {
          // 如果尚未设置部门ID，默认选择根节点
          if (!this.queryParams.deptId && this.deptOptions && this.deptOptions.length > 0) {
            const companyNode = this.deptOptions[0]
            this.$refs.tree.setCurrentKey(companyNode.id)
            this.queryParams.deptId = companyNode.id
          } else if (this.queryParams.deptId) {
            // 如果已经有部门ID，确保树节点选中状态与当前ID一致
            this.$refs.tree.setCurrentKey(this.queryParams.deptId)
          }

          // 所有初始化工作完成后，统一请求一次数据
          this.handleQuery()
        })
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      // 检查是否与之前选中的部门ID相同，避免重复请求
      if (this.queryParams.deptId !== data.id) {
        this.queryParams.deptId = data.id
        this.handleQuery()
      }
    },
    // 获取省份选项
    getProvinceOptions() {
      getDicts("sys_province").then(response => {
        this.provinceOptions = response.data
      })
    },
    // 获取房东选项
    getLandlordOptions() {
      return listLandlordAllocated().then(res => {
        console.log(res,'dkfnoi')
        const rows = res && res.rows ? res.rows : []
        this.landlordOptions = rows.map(item => ({
          id: item.userId,
          name: item.nickName,
          phone: item.phonenumber || '',
          displayName: `${item.nickName}${item.phonenumber ? ` (${item.phonenumber})` : ''}`
        }))
        // 如果有房东，自动选中第一个并过滤
        if (this.landlordOptions.length > 0) {
          // this.queryParams.landlordId = this.landlordOptions[0].id
          this.handleQuery()
        }
        // 重新渲染房东数据到列表中
        if (this.houseList && this.houseList.length > 0) {
          this.houseList.forEach(item => {
            if (item.landlordId) {
              const landlord = this.landlordOptions.find(l => l.id === item.landlordId)
              if (landlord) {
                item.landlordName = landlord.name
              }
            }
          })
        }
        // 如果对话框已打开，更新表单中房东的显示
        if (this.form && this.form.landlordId && this.open) {
          const landlord = this.landlordOptions.find(item => item.id === this.form.landlordId)
          if (landlord) {
            this.form.landlordName = landlord.name
          }
        }
        return this.landlordOptions
      })
    },
    // 搜索房东
    searchLandlord(query) {
      console.log('搜索房东被调用:', query)
      if (query && query.trim() !== '') {
        this.landlordSearchLoading = true

        // 使用 listLandlordAllocated API
        listLandlordAllocated({
          pageNum: 1,
          pageSize: 50,
          roleId: 100,
          nickName: query.trim()  // 使用昵称搜索
        }).then(res => {
          console.log('搜索房东结果:', res)
          const rows = res.rows || []
          const searchResults = rows.map(item => ({
            id: item.userId,
            name: item.nickName,
            phone: item.phonenumber || '',
            displayName: `${item.nickName}${item.phonenumber ? ` (${item.phonenumber})` : ''}`
          }))
          
          // 如果当前表单中有选中的房东，确保它在搜索结果中
          if (this.form.landlordObj && this.form.landlordObj.id) {
            const currentLandlord = this.form.landlordObj
            const existsInResults = searchResults.some(item => item.id === currentLandlord.id)
            if (!existsInResults) {
              // 将当前选中的房东添加到搜索结果的开头
              searchResults.unshift(currentLandlord)
            }
          }
          
          this.landlordOptions = searchResults
          this.landlordSearchLoading = false
        }).catch(err => {
          console.error('搜索房东失败:', err)
          this.landlordSearchLoading = false
          // 如果搜索失败，至少保留当前选中的房东
          if (this.form.landlordObj && this.form.landlordObj.id) {
            this.landlordOptions = [this.form.landlordObj]
          } else {
            this.landlordOptions = []
          }
        })
      } else {
        // 当查询为空时，如果有当前选中的房东，保留它
        if (this.form.landlordObj && this.form.landlordObj.id) {
          this.landlordOptions = [this.form.landlordObj]
        } else {
          this.landlordOptions = []
        }
      }
    },
    // 根据房东ID加载房东信息（编辑时使用）
    loadLandlordById(landlordId) {
      console.log('loadLandlordById 被调用，房东ID:', landlordId)
      if (landlordId) {
        return listLandlordAllocated({
          pageNum: 1,
          pageSize: 1000,
          roleId: 100
        }).then(res => {
          console.log('API返回的房东列表:', res)
          const rows = res.rows || []
          const landlord = rows.find(item => item.userId === landlordId)
          console.log('查找到的房东:', landlord)
          if (landlord) {
            // 添加到选项中，如果不存在的话
            const existingOption = this.landlordOptions.find(opt => opt.id === landlord.userId)
            if (!existingOption) {
              const landlordOption = {
                id: landlord.userId,
                name: landlord.nickName,
                phone: landlord.phonenumber || '',
                displayName: `${landlord.nickName}${landlord.phonenumber ? ` (${landlord.phonenumber})` : ''}`
              }
              this.landlordOptions.push(landlordOption)
              console.log('添加房东选项:', landlordOption)
            }
            return landlord
          } else {
            console.log('未找到匹配的房东，房东ID:', landlordId)
            return null
          }
        }).catch(err => {
          console.error('加载房东信息失败:', err)
          return null
        })
      }
      return Promise.resolve(null)
    },
    // 根据房东ID直接查询特定房东信息（用于编辑回显）
    loadSpecificLandlordById(landlordId) {
      console.log('loadSpecificLandlordById 被调用，房东ID:', landlordId)
      if (landlordId) {
        // 直接通过用户ID查询房东信息
        return getUser(landlordId).then(response => {
          console.log('直接查询房东信息结果:', response)
          if (response.code === 200 && response.data) {
            const userData = response.data
            // 检查用户是否有房东角色
            if (userData.roles && userData.roles.some(role => role.roleId === 100)) {
              return userData
            } else {
              console.log('用户不是房东角色')
              return null
            }
          }
          return null
        }).catch(err => {
          console.error('直接查询房东信息失败:', err)
          // 如果直接查询失败，回退到原来的方法
          return this.loadLandlordById(landlordId)
        })
      }
      return Promise.resolve(null)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        country: "",
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        addressNode: null,
        address: null,
        door: null,
        accessNum: null,
        monthPrice: null,
        balance: null,
        endDate: null,
        landlordId: this.$route.query.landlordId || null,
        landlordObj: null,
        deptId: null,
        remark: null
      }

      // 如果有指定房东ID，设置房东对象
      if (this.$route.query.landlordId && this.landlordOptions.length > 0) {
        const landlordId = Number(this.$route.query.landlordId)
        const landlord = this.landlordOptions.find(item => Number(item.id) === landlordId)
        if (landlord) {
          this.form.landlordObj = landlord
        }
      }

      this.resetForm("form")
      this.cityOptionsForm = []
      this.districtOptionsForm = []
      this.streetOptionsForm = []
      this.villageOptionsForm = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 清空房东名称、手机号和日期
      this.queryParams.landlordName = null
      this.queryParams.landlordPhone = null
      this.queryParams.startDate = null
      this.queryParams.endDate = null
      // 如果是从房东管理页面跳转过来，保留房东ID
      if (this.$route.query.landlordId) {
        this.queryParams.landlordId = this.$route.query.landlordId
      } else {
        this.queryParams.landlordId = null
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加账单"

      // 如果已选择了部门树节点，将该部门设置到表单的部门字段
      if (this.queryParams.deptId) {
        this.form.deptId = this.queryParams.deptId

        // 并尝试将部门ID匹配到地址选择
        this.setAddressFromDeptId(this.queryParams.deptId)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getHouse(id).then(response => {
        this.form = response.data
        // 确保房东ID为数字类型
        if (this.form.landlordId) {
          this.form.landlordId = Number(this.form.landlordId)

          // 直接根据房东ID查询具体的房东信息并设置到下拉框
          this.loadSpecificLandlordById(this.form.landlordId).then((landlordData) => {
            if (landlordData) {
              // 构造房东对象用于下拉框显示
              const landlordObj = {
                id: landlordData.userId,
                name: landlordData.nickName,
                phone: landlordData.phonenumber || '',
                displayName: `${landlordData.nickName}${landlordData.phonenumber ? ` (${landlordData.phonenumber})` : ''}`
              }
              
              // 确保房东选项在列表中
              const existingIndex = this.landlordOptions.findIndex(opt => opt.id === landlordObj.id)
              if (existingIndex === -1) {
                this.landlordOptions.unshift(landlordObj) // 添加到列表开头
              } else {
                this.landlordOptions[existingIndex] = landlordObj // 更新现有选项
              }
              
              // 设置房东对象，用于下拉框显示
              this.$set(this.form, 'landlordObj', landlordObj)
              this.$set(this.form, 'landlordName', landlordObj.name)
              
              // 强制触发视图更新
              this.$nextTick(() => {
                this.$forceUpdate()
              })
              
              console.log('设置房东对象成功:', this.form.landlordObj)
            } else {
              console.log('未找到房东信息，可能不是房东角色')
            }
          }).catch(err => {
            console.error('加载房东信息时出错:', err)
          })
        }

        this.open = true
        this.title = "修改账单"

        // 设置表单地址字段但不设置addressNode
        // 根据已有地址加载树节点
        this.loadAddressNodesForEdit()
      })
    },
    // 为编辑加载地址节点
    loadAddressNodesForEdit() {
      if (!this.form.province) return

      // 对于级联选择器，需要设置完整的路径数组
      const addressPath = []

      // 转换表单中的地址字段为数值类型
      const province = Number(this.form.province)
      const city = Number(this.form.city)
      const district = Number(this.form.district)
      const street = Number(this.form.street)
      const village = Number(this.form.village)

      // 首先添加公司节点
      addressPath.push(100)

      // 查找省级节点匹配
      const findMatchingNode = (nodes, targetValue) => {
        if (!nodes || !Array.isArray(nodes)) return null;

        for (const node of nodes) {
          if (node.value === targetValue) {
            return node;
          }

          if (node.children) {
            const found = findMatchingNode(node.children, targetValue);
            if (found) {
              return found;
            }
          }
        }

        return null;
      };

      // 从根节点开始匹配省份
      const companyNode = this.addressTreeOptions[0];
      if (companyNode && companyNode.children) {
        // 查找省
        const provinceNode = findMatchingNode(companyNode.children, province);
        if (provinceNode) {
          addressPath.push(provinceNode.value);

          // 查找市
          if (provinceNode.children && city) {
            const cityNode = findMatchingNode(provinceNode.children, city);
            if (cityNode) {
              addressPath.push(cityNode.value);

              // 查找区
              if (cityNode.children && district) {
                const districtNode = findMatchingNode(cityNode.children, district);
                if (districtNode) {
                  addressPath.push(districtNode.value);

                  // 查找街道
                  if (districtNode.children && street) {
                    const streetNode = findMatchingNode(districtNode.children, street);
                    if (streetNode) {
                      addressPath.push(streetNode.value);

                      // 查找村
                      if (streetNode.children && village) {
                        const villageNode = findMatchingNode(streetNode.children, village);
                        if (villageNode) {
                          addressPath.push(villageNode.value);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      // 如果找到匹配的路径，设置到表单中
      if (addressPath.length > 1) {
        this.form.addressNode = addressPath;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建API所需的数据对象
          const submitData = {
            ...this.form,
            // 确保以下字段为数字类型
            id: this.form.id ? Number(this.form.id) : undefined,
            province: this.form.province ? Number(this.form.province) : null,
            city: this.form.city ? Number(this.form.city) : null,
            district: this.form.district ? Number(this.form.district) : null,
            street: this.form.street ? Number(this.form.street) : null,
            village: this.form.village ? Number(this.form.village) : null,
            landlordId: this.form.landlordId ? Number(this.form.landlordId) : null,
            monthPrice: this.form.monthPrice ? Number(this.form.monthPrice) : null,
            balance: this.form.balance ? Number(this.form.balance) : null,
            deptId: this.form.deptId ? Number(this.form.deptId) : null
          }

          // 移除非API字段
          delete submitData.addressNode;
          delete submitData.landlordName;

          if (this.form.id != null) {
            updateHouse(submitData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error("更新失败:", error);
            })
          } else {
            addHouse(submitData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error("添加失败:", error);
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除房产编号为"' + ids + '"的数据项？').then(function() {
        return delHouse(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('door/house/export', {
        ...this.queryParams
      }, `house_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "房产导入"
      this.upload.open = true
      this.uploadFile = null
      this.uploadFileName = ""
      this.resetUploadState()
    },
    /** 下载模板操作 */
    importTemplate() {
      this.downloadTemplate("/door/house/importTemplate", "房产导入模板.xlsx")
    },
    // 触发文件选择
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    // 处理文件选择
    handleFileChange(e) {
      const files = e.target.files
      if (files && files.length > 0) {
        this.uploadFile = files[0]
        this.uploadFileName = files[0].name
      }
    },
    // 清除选择的文件
    clearUploadFile() {
      this.uploadFile = null
      this.uploadFileName = ""
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = ""
      }
    },
    // 提交导入请求
    submitImport() {
      if (!this.uploadFile) {
        this.$message.warning("请先选择要上传的Excel文件")
        return
      }

      this.upload.isUploading = true
      this.upload.statusText = "正在导入数据..."
      this.upload.progress = 50

      // 直接处理导入文件流
      importData(this.uploadFile).then(response => {
        this.upload.isUploading = false
        this.upload.progress = 100
        this.upload.statusText = "导入完成，正在下载结果文件..."
        this.upload.progressStatus = 'success'

        // 直接下载返回的文件流
        const url = window.URL.createObjectURL(response)
        const a = document.createElement('a')
        a.href = url
        a.download = `房产导入结果_${new Date().getTime()}.xlsx`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)

        this.$message.success("导入完成，结果文件已下载")

        // 刷新列表
        this.getList()

        // 2秒后关闭对话框
        setTimeout(() => {
          this.closeImportDialog()
        }, 2000)
      }).catch(error => {
        this.upload.isUploading = false
        this.upload.progress = 0
        this.upload.statusText = "导入失败"
        this.upload.progressStatus = 'exception'

        console.error('导入失败:', error)
        let errorMessage = "导入失败"

        if (error.response) {
          // 如果有响应，尝试解析错误信息
          if (error.response.data && error.response.data.type === 'application/json') {
            // 如果返回的是JSON错误信息，需要转换
            const reader = new FileReader()
            reader.onload = () => {
              try {
                const errorData = JSON.parse(reader.result)
                errorMessage = errorData.msg || "导入失败"
                this.$message.error(errorMessage)
              } catch (e) {
                this.$message.error("导入失败，请检查文件格式")
              }
            }
            reader.readAsText(error.response.data)
          } else {
            errorMessage = error.response.statusText || "导入失败"
            this.$message.error(errorMessage)
          }
        } else {
          errorMessage = error.message || "网络错误"
          this.$message.error(errorMessage)
        }
      })
    },

    // 重置上传状态
    resetUploadState() {
      this.upload.isUploading = false
      this.upload.statusText = "准备上传文件..."
      this.upload.progress = 0
      this.upload.progressStatus = null
    },
    // 关闭导入对话框
    closeImportDialog() {
      this.upload.open = false
      this.resetUploadState()
      this.clearUploadFile()
    },
    /** 资料管理按钮操作 */
    handleDocuments(row) {
      this.$router.push({
        path: '/door/adsl/index',
        query: {
          houseId: row.id,
          houseAddress: row.province + row.city + row.district + row.street + row.village + row.address + row.door
        }
      })
    },
    // 省份变更
    provinceChange(val) {
      this.queryParams.city = null
      this.queryParams.district = null
      this.queryParams.street = null
      this.queryParams.village = null
      this.cityOptions = []
      this.districtOptions = []
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_city_" + val).then(response => {
          this.cityOptions = response.data
        })
      }
    },
    // 城市变更
    cityChange(val) {
      this.queryParams.district = null
      this.queryParams.street = null
      this.queryParams.village = null
      this.districtOptions = []
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_district_" + val).then(response => {
          this.districtOptions = response.data
        })
      }
    },
    // 区县变更
    districtChange(val) {
      this.queryParams.street = null
      this.queryParams.village = null
      this.streetOptions = []
      this.villageOptions = []
      if (val) {
        getDicts("sys_street_" + val).then(response => {
          this.streetOptions = response.data
        })
      }
    },
    // 街道变更
    streetChange(val) {
      this.queryParams.village = null
      this.villageOptions = []
      if (val) {
        getDicts("sys_village_" + val).then(response => {
          this.villageOptions = response.data
        })
      }
    },

    // 处理地址选择
    handleAddressNodeSelect(val) {
      if (!val || val.length === 0) {
        // 清空所有字段
        this.form.province = null
        this.form.city = null
        this.form.district = null
        this.form.street = null
        this.form.village = null
        // 清空部门ID
        this.form.deptId = null
        return
      }

      // 级联选择器传入的是完整路径数组，包含了所有选中层级的值
      // 忽略第一个节点(公司)，根据层级设置表单数据
      const path = val.slice(1)

      // 重置所有地址字段
      this.form.province = null
      this.form.city = null
      this.form.district = null
      this.form.street = null
      this.form.village = null

      // 根据节点路径层级设置对应地址字段
      // 假设路径结构为：公司 -> 省 -> 市 -> 区 -> 街道/镇 -> 村
      for (let i = 0; i < path.length; i++) {
        const nodeValue = path[i]
        switch (i) {
          case 0: // 省
            this.form.province = nodeValue // 存储为数值
            break
          case 1: // 市
            this.form.city = nodeValue // 存储为数值
            break
          case 2: // 区
            this.form.district = nodeValue // 存储为数值
            break
          case 3: // 街道/镇
            this.form.street = nodeValue // 存储为数值
            break
          case 4: // 村
            this.form.village = nodeValue // 存储为数值
            break
        }
      }

      // 同步设置表单中的部门ID为地址树中最后一级选择的节点ID
      // 由于我们使用了部门树构建地址树，所以地址节点ID就是部门ID
      if (path.length > 0) {
        // 地址树最后一级节点的值即为对应部门ID
        const selectedNodeValue = path[path.length - 1]
        this.form.deptId = selectedNodeValue
      }
    },

    // 根据标签在特定父节点下查找节点
    findNodeByLabelInParent(label, parentValue) {
      const findNode = (nodes, parent) => {
        if (!nodes) return null

        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]

          if (node.value === parent) {
            // 在子节点中查找匹配标签的节点
            if (node.children) {
              for (let j = 0; j < node.children.length; j++) {
                const child = node.children[j]
                if (child.label && child.label.indexOf(label) !== -1) {
                  return child
                }
              }
            }
            return null
          }

          if (node.children) {
            const found = findNode(node.children, parent)
            if (found) return found
          }
        }

        return null
      }

      return findNode(this.addressTreeOptions, parentValue)
    },

    // 根据标签查找节点
    findNodeByLabel(label) {
      const findNode = (nodes) => {
        if (!nodes) return null
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]
          if (node.label && node.label.indexOf(label) !== -1) {
            return node
          }
          if (node.children) {
            const found = findNode(node.children)
            if (found) {
              return found
            }
          }
        }
        return null
      }

      return findNode(this.addressTreeOptions)
    },
    // 从部门树构建地址树
    buildAddressTreeFromDeptTree() {
      if (!this.deptOptions || this.deptOptions.length === 0) return

      // 将部门树转换为地址树结构
      const convertToAddressTree = (deptNodes) => {
        if (!deptNodes || deptNodes.length === 0) return []

        return deptNodes.map(dept => {
          const addressNode = {
            value: dept.id, // 使用部门ID作为地址节点ID
            label: dept.label, // 使用部门名称作为地址节点名称
            disabled: dept.disabled
          }

          // 递归处理子节点
          if (dept.children && dept.children.length > 0) {
            addressNode.children = convertToAddressTree(dept.children)
          }

          return addressNode
        })
      }

      // 创建根节点
      this.addressTreeOptions = [{
        value: 100,
        label: this.deptOptions[0].label || "公司",
        disabled: false,
        children: convertToAddressTree(this.deptOptions[0].children || [])
      }]
    },
    // 根据部门ID设置地址节点
    setAddressFromDeptId(deptId) {
      if (!deptId) return

      // 查找部门树中的节点
      const findDeptPath = (nodes, id, path = []) => {
        if (!nodes || !Array.isArray(nodes)) return null

        for (const node of nodes) {
          const currentPath = [...path, node]

          if (node.id === id) {
            return currentPath
          }

          if (node.children) {
            const found = findDeptPath(node.children, id, currentPath)
            if (found) return found
          }
        }

        return null
      }

      // 获取部门的路径
      const deptPath = findDeptPath(this.deptOptions, deptId)
      if (!deptPath || deptPath.length === 0) return

      // 构建地址路径
      const addressPath = [100] // 根节点ID

      // 依次将路径中的节点ID添加到地址路径中
      // 跳过第一个节点(根节点)
      for (let i = 1; i < deptPath.length; i++) {
        addressPath.push(deptPath[i].id)
      }

      // 设置地址路径到表单
      if (addressPath.length > 1) {
        this.form.addressNode = addressPath

        // 提取各级地址值
        // 跳过根节点
        for (let i = 1; i < deptPath.length; i++) {
          switch (i) {
            case 1: // 省
              this.form.province = deptPath[i].id
              break
            case 2: // 市
              this.form.city = deptPath[i].id
              break
            case 3: // 区
              this.form.district = deptPath[i].id
              break
            case 4: // 街道
              this.form.street = deptPath[i].id
              break
            case 5: // 村
              this.form.village = deptPath[i].id
              break
          }
        }
      }
    },
    // 房东变更
    handleLandlordChange(value) {
      console.log('房东变更被调用:', value)
      if (value && value.id) {
        // 使用 $set 确保响应式更新
        this.$set(this.form, 'landlordId', value.id)
        this.$set(this.form, 'landlordName', value.name)
        this.$set(this.form, 'landlordObj', value)
        
        // 强制触发视图更新
        this.$nextTick(() => {
          this.$forceUpdate()
        })
        
        console.log('房东变更成功:', {
          landlordId: this.form.landlordId,
          landlordName: this.form.landlordName,
          landlordObj: this.form.landlordObj
        })
      } else {
        // 清空房东信息
        this.$set(this.form, 'landlordId', null)
        this.$set(this.form, 'landlordName', null)
        this.$set(this.form, 'landlordObj', null)
        
        // 强制触发视图更新
        this.$nextTick(() => {
          this.$forceUpdate()
        })
        
        console.log('房东信息已清空')
      }
    }

  }
}
</script>

<style scoped>
.main-content {
  height: calc(100vh - 124px);
  overflow: hidden;
}

.app-container {
  padding: 10px;
  height: 100%;
  overflow: hidden;
}

.el-form-item {
  margin-bottom: 18px;
}

.default-theme {
  height: 100%;
}

.splitpanes.default-theme .splitpanes__pane {
  background-color: #fff;
  overflow: auto;
}

.splitpanes--vertical > .splitpanes__splitter {
  min-width: 6px;
}

/* 表格样式优化 */
.el-table {
  margin-top: 8px;
}

.el-table .el-table__header th {
  background-color: #f5f7fa;
}

.el-table .el-table__row:hover {
  background-color: #f0f7ff;
}

/* 表单样式优化 */
.el-dialog__body {
  padding: 20px 30px 10px 30px;
}

/* 导入对话框样式 */
.import-container {
  padding: 10px 0;
}

.import-tips {
  margin-bottom: 15px;
}

.upload-area {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  padding: 30px 0;
  margin: 10px 0;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-area .el-icon-upload {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

.file-info {
  display: flex;
  align-items: center;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin: 10px 0;
  background-color: #f9f9f9;
}

.file-info i {
  color: #909399;
  margin-right: 8px;
  font-size: 18px;
}

/* 导入进度样式 */
.import-progress {
  padding: 20px 0;
}

.progress-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.progress-header i {
  margin-right: 8px;
  color: #409EFF;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.progress-details {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  color: #606266;
  font-weight: 500;
}

.detail-item .value {
  font-weight: bold;
}

.detail-item .value.success {
  color: #67c23a;
}

.detail-item .value.error {
  color: #f56c6c;
}

.import-log {
  margin-top: 15px;
}

.log-content {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.5;
  color: #606266;
}

/* 进度条样式调整 */
.el-progress {
  margin: 10px 0;
}

.el-progress__text {
  font-weight: bold;
}
</style>

